package org.eweb4j.mvc.validator;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.eweb4j.mvc.config.bean.FieldConfigBean;
import org.eweb4j.mvc.config.bean.ValidatorConfigBean;


/**
 * 对必填项的验证
 * 
 * @author cfuture.aw
 * 
 */
public class RequriedValidator implements ValidatorIF {
	public Map<String, String> validate(ValidatorConfigBean val,
			Map<String, String[]> map, HttpServletRequest request) {
		Map<String, String> valError = new HashMap<String, String>();
		for (FieldConfigBean f : val.getField()) {
			String[] value = map.get(f.getName());
			String mess = f.getMessage();
			if (mess.length() == 0)
				mess = " %s-validator : your input { %s = %s } must have content ";

			if (value == null || value.length == 0)
				valError.put(f.getName(),
						String.format(mess, val.getName(), f.getName(), value));
			else
				for (String v : value) {
					if (v != null && v.length() > 0)
						continue;

					valError.put(f.getName(),
							String.format(mess, val.getName(), f.getName(), v));
				}

			request.setAttribute(f.getName(), value);
		}

		return valError.isEmpty() ? null : valError;
	}
}
